package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"shop/model/mysql"
	"shop/model/redisinit"
	"shop/shoprpc/internal/svc"
	"shop/shoprpc/shoprpc"
	"strconv"
	"time"
)

type ShopListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShopListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShopListLogic {
	return &ShopListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ShopListLogic) ShopList(in *shoprpc.ShopListRequest) (*shoprpc.ShopListResponse, error) {
	// todo: add your logic here and delete this line

	var findshop []mysql.Products
	page := in.Page
	if page <= 0 {
		page = 1
	}
	size := in.Size
	switch {
	case size > 100:
		size = 100
	case size <= 0:
		size = 10
	}
	offset := (page - 1) * size
	key := "list" + strconv.Itoa(int(offset))
	get := redisinit.Rdb.Get(key)
	if get.Val() == "" {
		mysql.DB.Offset(int(offset)).Limit(int(size)).Order("price desc").Find(&findshop)
		marshal, _ := json.Marshal(&findshop)
		redisinit.Rdb.Set(key, marshal, time.Hour*24)
		fmt.Println("mysql")
	} else {
		json.Unmarshal([]byte(get.Val()), &findshop)
		fmt.Println("redis")
	}
	var lists []*shoprpc.ShopList
	for _, m := range findshop {
		list := shoprpc.ShopList{
			Id:        int64(m.ID),
			Shopname:  m.Shopname,
			Shopimage: m.Shopimage,
			Price:     m.Price,
			Stock:     m.Stock,
			Userid:    m.Userid,
		}
		lists = append(lists, &list)
	}
	return &shoprpc.ShopListResponse{
		List: lists,
	}, nil
}
